package org.lg.multidatabase.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.lg.multidatabase.config.DynamicDataSource;
import org.lg.multidatabase.enumeration.DataSourceKeyEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: DynamicDataSourceAspect
 * @Author: lvgang
 * @Date: 2022/4/24 10:03
 * @Description: 所有Controller，AOP。通过此AOP切换数据库
 */
@Component
@Aspect
@Slf4j
public class DynamicDataSourceAspect {

    /**
     * 前置AOP
     * @param point
     */
    @Before("within(org.lg.multidatabase.controller.*)")
    public void before(JoinPoint point){

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();

        //获取 gateway转发 请求头信息
        String gateway_host = request.getHeader("Host");

        log.info("=====Start===DynamicDataSourceAspect===before===");
        log.info("URL:{}",url);

        //是否可以匹配上，如果没有办法匹配上，就使用默认
        boolean temp = false;

        for(DataSourceKeyEnum dataSourceKeyEnum : DataSourceKeyEnum.values()){
            if(url.toUpperCase().indexOf(dataSourceKeyEnum.getDomain().toUpperCase())>=0){
                DynamicDataSource.dataSourceKey.set(dataSourceKeyEnum.getIndex());
                log.info("DataSource:{},{},{}",dataSourceKeyEnum.getIndex(),dataSourceKeyEnum.getName(),dataSourceKeyEnum.getDomain());
                temp = true;
            }
        }

        if(!temp){
            DynamicDataSource.dataSourceKey.set(DataSourceKeyEnum.ONE.getIndex());
            log.info("Default DataSource:{},{},{}", DataSourceKeyEnum.ONE.getIndex(),DataSourceKeyEnum.ONE.getName(),DataSourceKeyEnum.ONE.getDomain());
        }
    }


}
